import {
  addPermission,
  DeletePermission,
  deleteRolePermission,
  getPermissions,
  getRoles,
  putPermission,
} from '@/services/ant-design-pro/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormSelect,
  ProFormText,
  ProFormTreeSelect,
  ProTable,
} from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { App, Button, Popconfirm, Switch, Tag } from 'antd';
import lodash from 'lodash';
import React, { useRef, useState } from 'react';

type GithubIssueItem = {
  url: string;
  id: number;
  number: number;
  title: string;
  labels: {
    name: string;
    color: string;
  }[];
  state: string;
  comments: number;
  created_at: string;
  updated_at: string;
  closed_at?: string;
};

const Authority: React.FC<any> = ({ transTab }) => {
  const [addOrEdit, setAddOrEdit] = useState('add');
  const [currentRow, setCurrentRow] = useState<any>();
  const [modalVisit, setModalVisit] = useState(false);
  const actionRef = useRef<ActionType>();
  const [treeData, setTreeData] = useState<any>([]);
  const [expandeKeys, setExpandeKeys] = useState<any>([]);
  const intl = useIntl();

  const { message } = App.useApp();
  async function requestData(val: any) {
    const res = {
      data: [],
      total: 0,
    };
    const data: any = await getPermissions({ params: val });
    if (data.code === 0) {
      res.data = data.msg;
      setTreeData(data.msg);
    }
    return Promise.resolve(res);
  }
  // 查找路径，并返回路径数组和目标节点引用
  function findPathToNode(tree: any[], targetId: string): string[] {
    const path: string[] = [];

    function dfs(nodes: any[]): boolean {
      for (const node of nodes) {
        path.push(node.id);
        if (node.id === targetId) {
          return true;
        }
        if (node.children && dfs(node.children)) {
          return true;
        }
        path.pop();
      }
      return false;
    }

    dfs(tree);
    return path;
  }

  // 收集指定节点的所有后代 ID（包括自己）
  function collectDescendantIds(tree: any[], targetId: string): string[] {
    const result: string[] = [];

    // 用于找到目标节点
    function findTargetNode(nodes: any[]): any | null {
      for (const node of nodes) {
        if (node.id === targetId) {
          return node;
        }
        if (node.children) {
          const found = findTargetNode(node.children);
          if (found) return found;
        }
      }
      return null;
    }

    // 用于收集目标节点及其所有子节点的 id
    function collectIds(node: any) {
      result.push(node.id);
      if (node.children && node.children.length > 0) {
        for (const child of node.children) {
          collectIds(child);
        }
      }
    }

    const targetNode = findTargetNode(tree);
    if (targetNode) {
      collectIds(targetNode);
    }

    return result;
  }

  function signTreeDisabled(tree: any, id: any) {
    function loop(arr: any) {
      for (let i = 0; i < arr.length; i++) {
        const element = arr[i];
        if (element.id === id) {
          element.disabled = true;
        } else {
          element.disabled = false;
        }
        if (element.children) {
          loop(element.children);
        }
      }
    }
    loop(tree);
  }
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'component.permissionName',
        defaultMessage: '权限名',
      }),
      dataIndex: 'name',
      ellipsis: true,
      // tooltip: '标题过长会自动收缩',
    },
    {
      title: intl.formatMessage({
        id: 'component.permissionType',
        defaultMessage: '权限类型',
      }),
      dataIndex: 'type',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'component.theRoleWithThisPermission',
        defaultMessage: '拥有该权限的角色',
      }),
      dataIndex: 'character',
      hideInSearch: true,
      tooltip: intl.formatMessage({
        id: 'component.pageWithoutRole',
        defaultMessage: '非叶子菜单不需要配置角色,因为没有页面',
      }),
      render(dom, record: any) {
        // if (record.type === '菜单' && record.children) {
        //   return <Typography.Text disabled>{intl.formatMessage({
        //     id: 'component.theRoleCannotHaveThisPermission',
        //     defaultMessage: '角色不可拥有该权限',
        //   })}</Typography.Text>;
        // } else {
        if (record.character && record.character.length > 0) {
          const res = record.character.map((val: any) => {
            return (
              <Tag
                key={val.id}
                onClose={async () => {
                  const data = lodash.cloneDeep(record);
                  data.character = data.character.filter((item: any) => {
                    return item.id === val.id;
                  });
                  const res: any = await deleteRolePermission({ data });
                  if (res.code === 0) {
                    actionRef.current?.reload();
                    message.success('权限修改成功');
                  } else {
                    message.info(res.msg);
                    actionRef.current?.reload();
                  }
                }}
                onClick={(e: any) => transTab('角色管理', e.target.outerText)}
                style={{ margin: '3px 3px', cursor: 'pointer' }}
                closable
                color="geekblue"
              >
                {val.name}
              </Tag>
            );
          });
          return res;
        } else {
          return '';
        }
        // }
      },
    },
    {
      title: intl.formatMessage({
        id: 'pages.searchTable.titleOption',
        defaultMessage: '操作',
      }),
      width: '120px',
      valueType: 'option',
      ellipsis: true,
      key: 'option',
      render: (text, record: any) => [
        <Button
          onClick={() => {
            signTreeDisabled(treeData, record.id);
            setAddOrEdit('edit');
            setCurrentRow(record);
            setModalVisit(true);
          }}
          key="edit"
          size="small"
          type="primary"
          ghost
        >
          {intl.formatMessage({
            id: 'component.edit',
            defaultMessage: '编辑',
          })}
        </Button>,
        <Popconfirm
          key="delete"
          title={intl.formatMessage({
            id: 'component.deletePermission',
            defaultMessage: '删除权限',
          })}
          description={intl.formatMessage(
            {
              id: 'component.requireDeletePermission',
              defaultMessage: '是否删除（{name}）权限？',
            },
            { name: record.name },
          )}
          onConfirm={async () => {
            const res: any = await DeletePermission({ data: { id: record.id } });
            if (res.code === 0) {
              message.success('删除成功');
              actionRef.current?.reload();
            } else {
              message.info(res.msg);
            }
          }}
          onCancel={() => {}}
          okText="Yes"
          cancelText="No"
        >
          <Button size="small" danger>
            {intl.formatMessage({
              id: 'component.delete',
              defaultMessage: '删除',
            })}
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  function getAllExpandKeys(tree: any) {
    const res: any = [];
    function loop(arr: any) {
      arr.forEach((item: any) => {
        res.push(item.id);
        if (item.children) {
          loop(item.children);
        }
      });
    }
    loop(tree);
    setExpandeKeys(res);
  }
  return (
    <>
      <ModalForm
        title={
          addOrEdit === 'add'
            ? intl.formatMessage({
                id: 'component.createPermission',
                defaultMessage: '新建权限',
              })
            : intl.formatMessage({
                id: 'component.modifyPermission',
                defaultMessage: '修改权限',
              })
        }
        open={modalVisit}
        autoFocusFirstInput
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setModalVisit(false),
        }}
        width={400}
        onFinish={async (val: any) => {
          let pathPermission: any = null;
          let descendants: any = null;
          val.character =
            val.character &&
            val.character.map((item: any) => {
              return {
                id: item,
              };
            });

          val.parentId = val.parentId ? val.parentId.value : null;
          pathPermission = findPathToNode(treeData, val.parentId);
          if (addOrEdit === 'add') {
            descendants = collectDescendantIds(treeData, val.parentId);
            const res: any = await addPermission({ data: { ...val, pathPermission } });
            if (res.code === 0) {
              message.success('权限添加成功');
              actionRef.current?.reload();
            } else {
              message.info(res.msg);
            }
          } else {
            descendants = collectDescendantIds(treeData, currentRow.id);
            const res: any = await putPermission({
              data: { ...val, id: currentRow.id, pathPermission, descendants },
            });
            if (res.code === 0) {
              message.success('权限修改成功');
              actionRef.current?.reload();
            } else {
              message.info(res.msg);
            }
          }
          setModalVisit(false);
        }}
      >
        <ProFormText
          name="name"
          label={intl.formatMessage({
            id: 'component.permissionName',
            defaultMessage: '权限名',
          })}
          placeholder={intl.formatMessage({
            id: 'component.enterPermissionName',
            defaultMessage: '请输入权限名',
          })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'component.enterPermissionName',
                defaultMessage: '请输入权限名',
              }),
            },
          ]}
          initialValue={currentRow && currentRow.name}
        />
        <ProFormText
          name="type"
          label={intl.formatMessage({
            id: 'component.permissionType',
            defaultMessage: '权限类型',
          })}
          placeholder={intl.formatMessage({
            id: 'component.enterPermissionType',
            defaultMessage: '请输入权限类型',
          })}
          initialValue={currentRow && currentRow.type}
        />

        <ProFormTreeSelect
          name="parentId"
          label={intl.formatMessage({
            id: 'component.parentLevelPermissions',
            defaultMessage: '父级权限',
          })}
          tooltip={intl.formatMessage({
            id: 'component.defaultFirstLevelPermission',
            defaultMessage: '默认为空则设置为一级权限',
          })}
          placeholder={intl.formatMessage({
            id: 'component.selectParentPermission',
            defaultMessage: '请选择父级权限,空则设为一级权限',
          })}
          allowClear
          secondary
          initialValue={(function () {
            const res = {
              value: currentRow && currentRow.parentId,
            };
            return res;
          })()}
          request={async function () {
            return Promise.resolve(treeData);
          }}
          fieldProps={{
            treeDefaultExpandedKeys: [currentRow && currentRow.parentId],
            suffixIcon: null,
            filterTreeNode: true,
            showSearch: true,
            popupMatchSelectWidth: false,
            labelInValue: true,
            autoClearSearchValue: true,
            treeNodeFilterProp: 'name',
            fieldNames: {
              label: 'name',
              value: 'id',
            },
          }}
        />
        {/* {currentRow && currentRow.type === '菜单' && currentRow && currentRow.children ? (
          ''
        ) : ( */}
        {(currentRow && currentRow.type === '菜单') ||
        (currentRow && currentRow.type === '按钮') ? (
          <ProFormSelect
            name="character"
            label={intl.formatMessage({
              id: 'component.theRoleWithThisPermission',
              defaultMessage: '拥有该权限的角色',
            })}
            initialValue={(function () {
              const res =
                currentRow &&
                currentRow.character &&
                currentRow.character.map((item: any) => {
                  return item.id;
                });
              return res;
            })()}
            fieldProps={{
              mode: 'multiple',
              fieldNames: {
                label: 'name',
                value: 'id',
              },
            }}
            request={async () => {
              let res = [];
              const data = await getRoles({ params: { current: '1', pageSize: '999999999' } });
              if (data.code === 0) {
                res = data.msg;
              }
              return Promise.resolve(res);
            }}
            placeholder={intl.formatMessage({
              id: 'component.selectRoleWithPermission',
              defaultMessage: '请选择拥有该权限的角色',
            })}
          />
        ) : (
          ''
        )}
      </ModalForm>
      <ProTable<GithubIssueItem>
        expandable={{
          expandedRowKeys: expandeKeys,
          onExpandedRowsChange: (val: any) => {
            setExpandeKeys(val);
          },
        }}
        columns={columns}
        actionRef={actionRef}
        request={requestData}
        editable={{
          type: 'multiple',
        }}
        scroll={{
          x: true,
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
          onChange() {},
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={false}
        // pagination={{
        //   onChange: (page) => console.log(page),
        // }}
        dateFormatter="string"
        headerTitle={intl.formatMessage({
          id: 'pages.admin.rightsManagement',
          defaultMessage: '权限管理',
        })}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              signTreeDisabled(treeData || [], '');
              setAddOrEdit('add');
              setCurrentRow(null);
              setModalVisit(true);
            }}
            type="primary"
          >
            {intl.formatMessage({
              id: 'pages.searchTable.new',
              defaultMessage: '新建',
            })}
          </Button>,
          <Switch
            key="switch"
            onClick={(val: any) => {
              if (val) {
                getAllExpandKeys(treeData);
              } else {
                getAllExpandKeys([]);
              }
            }}
            checkedChildren={intl.formatMessage({
              id: 'component.tagSelect.collapse',
              defaultMessage: '收起',
            })}
            unCheckedChildren={intl.formatMessage({
              id: 'component.tagSelect.expand',
              defaultMessage: '展开',
            })}
          ></Switch>,
        ]}
      />
    </>
  );
};

export default Authority;
